package mt;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class GoogleMT extends C2EMT {

	public static String label = "Google";

	@Override
	public String translate(String query) throws Exception {
		String encoding = "utf-8";
		// String from = "zh-CN";
		// String to = "en";
		// String query = "我爱我的家乡";
		String result = "";
		URLConnection uc =null;
		try {

			query = URLEncoder.encode(query, encoding);
			String url = "http://translate.google.cn/translate_a/t?"
					+ "client=t&text="
					+ query
					+ "&hl=zh-CN&sl=zh-CH&tl=en&multires=1&prev=btn&ssel=0&tsel=0&sc=1";

//			System.setProperty("proxySet", "true");
//			System.setProperty("http.proxyHost", "proxy.corp.youdao.com");
//			System.setProperty("http.proxyPort", "8080");
//
//			System.setProperty("http.proxyUser", "guojing");
//			System.setProperty("http.proxyPassword", "Guojing1");
			URL u = new URL(url);
			uc = u.openConnection();
			uc
					.setRequestProperty("User-Agent",
							"Mozilla/5.0 (Windows NT 5.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1");
			uc.setRequestProperty("Host", "translate.google.cn");
			uc.setRequestProperty("Accept", "text/css,*/*;q=0.1");
			uc.setRequestProperty("Accept-Language",
					"en-us,en;q=0.7,zh-cn;q=0.3");
			// uc.setRequestProperty( "Accept-Encoding","gzip, deflate");
			uc.setRequestProperty("Accept-Charset",
					"GB2312,utf-8;q=0.7,*;q=0.7");
			uc.setRequestProperty("Referer",
					"http://translate.google.cn/?hl=zh-CN&tab=wT");

			// byte[] bys = IOUtils.toByteArray(uc.getInputStream());
			// String str = new String(bys, "UTF-8");
			BufferedReader r;
			r = new BufferedReader(new InputStreamReader(uc.getInputStream(),
					encoding));
			String inputLine;
			while ((inputLine = r.readLine()) != null)
				result += inputLine;

			result = result.substring(4);
			result = result.substring(0, result.indexOf("\""));

			// System.out.println(result);
			r.close();
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			System.setProperty("proxySet", "false");
			uc=null;
		}
		if (result.charAt(result.length() - 1) == '\\')
			throw new Exception();
		return segment(result.trim());
	}
}
